import React, { Suspense, useEffect } from 'react';
import {Routes, Route, Navigate, Outlet} from 'react-router-dom';
import { RouteConfig, useMenuStore } from '@/store/menuStore';
import LoadingSpinner from '@/components/LoadingSpinner';
import PageContainer from '@/components/PageContainer';
import { getToken } from '@/utils/auth.ts';

// 路由保护组件
const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
    const token = getToken();
    return token ? <>{children}</> : <Navigate to="/logineeeee" replace />;
};

// 定义一个组件，用于设置当前路由
const SetCurrentRoute = ({ route }: { route: RouteConfig }) => {
    const { setCurrentRoute } = useMenuStore();
    useEffect(() => {
        setCurrentRoute(route);
        return () => {
            // 在离开路由时清除当前路由，或者根据需求保留
            // setCurrentRoute(null);
        };
    }, [route, setCurrentRoute]);
    return null;
};
const AppRouter = () => {
    const { getRoutes, loadMenuFromApi, isMenuLoaded, isMenuLoading } =
        useMenuStore();

    // 加载菜单数据
    useEffect(() => {
        if (!isMenuLoaded && !isMenuLoading) {
            loadMenuFromApi();
        }
    }, [isMenuLoaded, isMenuLoading, loadMenuFromApi]);
    // 如果菜单正在加载中，显示加载状态
    if (!isMenuLoaded || isMenuLoading) {
        return <LoadingSpinner />;
    }

    const routes = getRoutes();
    const renderRoute = (route: RouteConfig) => {
        const RouteWrapper = route.element ? (
            React.createElement(route.element)
        ) : (
            <Outlet />
        );
        return (
            <PageContainer title={route.name}>
                <SetCurrentRoute route={route} />
                {RouteWrapper}
            </PageContainer>
        );
    };

    // 递归渲染路由
    const renderRoutes = (routes: RouteConfig[]) => {
        return routes.map((route) => {
            // 处理重定向
            if (route.redirect) {
                return (
                    <Route
                        key={route.menuName || route.path}
                        path={route.path}
                        element={<Navigate to={route.redirect} replace />}
                    />
                );
            }

            // 处理嵌套路由
            if (route.children && route.children.length > 0) {
                return (
                    <Route
                        key={route.menuName || route.path}
                        path={route.path}
                        element={
                            route.isProtected ? (
                                <ProtectedRoute>
                                    {renderRoute(route)}
                                </ProtectedRoute>
                            ) : (
                                renderRoute(route)
                            )
                        }
                    >
                        {renderRoutes(route.children)}
                    </Route>
                );
            }

            // 处理普通路由
            return (
                <Route
                    key={route.menuName || route.path}
                    path={route.path}
                    element={
                        route.isProtected ? (
                            <ProtectedRoute>
                                {renderRoute(route)}
                            </ProtectedRoute>
                        ) : (
                            renderRoute(route)
                        )
                    }
                />
            );
        });
    };


    return (
        <Suspense fallback={<LoadingSpinner />}>
            <Routes>{renderRoutes(routes)}</Routes>
        </Suspense>
    );
};

export default AppRouter;
